package com.ltedu.common.utils;

import com.ltedu.common.contants.AuthConstants;
import com.ltedu.common.contants.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {

    /**
     * token过期时间
     */
    public static final long EXPIRE = 1000 * 60 * 60 * 24;

    /**
     * 秘钥
     */
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * getJwtToken: 生成token字符串的方法 <br/>
     * @auther: Jerry
     * @param: [id, nickname]
     * @date: 2020/11/27 12:43
     * @return: java.lang.String
     */
    public static String createJwtToken(Long id, String nickname){
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")

                .setSubject("ltedu-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))

                // 设置token主体部分 ，存储用户信息
                .claim("id", id)
                .claim("nickname", nickname)

                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * getJwtTokenByUsername: 生成token字符串的方法 <br/>
     * @auther: Jerry
     * @param: [id, nickname]
     * @date: 2020/11/27 12:43
     * @return: java.lang.String
     */
    public static String createJwtTokenByUsername(Long id, String username){
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")

                .setSubject("ltedu-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))

                // 设置token主体部分 ，存储用户信息
                .claim("id", id)
                .claim("username", username)

                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) { return false; }
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader(AuthConstants.AUTHORIZATION);
            if(StringUtils.isEmpty(jwtToken)) { return false; }
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token字符串获取会员id
     * @param request
     * @return
     */
    public static Integer getJwtTokenByMemberId(HttpServletRequest request) {
        String jwtToken = request.getHeader(AuthConstants.AUTHORIZATION);
        if(StringUtils.isEmpty(jwtToken)) { return null; }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (Integer)claims.get("id");
    }

    /**
     * 根据token字符串获取用户名
     * @param request
     * @return
     */
    public static String getJwtTokenByUsername(HttpServletRequest request) {
        String jwtToken = request.getHeader(AuthConstants.AUTHORIZATION);
        if(StringUtils.isEmpty(jwtToken)) { return null; }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("username");
    }
}
